<template>
  <view class="address-input-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">账单录入</text>
      <text class="nav-save" @click="saveAddress">保存</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-container">
      <uni-forms ref="form" :model="formData" :rules="rules">
        <!-- 地区信息 -->
        <view class="form-section">
          <view class="section-title">地区信息</view>
          
          <uni-forms-item label="省份" required>
            <uni-data-select
              v-model="formData.province"
              :localdata="provinceList"
              placeholder="请选择省份"
              @change="onProvinceChange"
            />
          </uni-forms-item>
          
          <uni-forms-item label="城市" required>
            <uni-data-select
              v-model="formData.city"
              :localdata="cityList"
              placeholder="请选择城市"
              @change="onCityChange"
            />
          </uni-forms-item>
          
          <uni-forms-item label="区县" required>
            <uni-data-select
              v-model="formData.district"
              :localdata="districtList"
              placeholder="请选择区县"
              @change="onDistrictChange"
            />
          </uni-forms-item>
          
          <uni-forms-item label="街道" required>
            <uni-data-select
              v-model="formData.street"
              :localdata="streetList"
              placeholder="请选择街道"
              @change="onStreetChange"
            />
          </uni-forms-item>
          
          <uni-forms-item label="村/社区" required>
            <uni-data-select
              v-model="formData.village"
              :localdata="villageList"
              placeholder="请选择村/社区"
              @change="onVillageChange"
            />
          </uni-forms-item>
        </view>

        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">基本信息</view>
          
          <uni-forms-item label="详细地址" required>
            <uni-easyinput
              v-model="formData.address"
              placeholder="请输入详细地址"
              :clearable="true"
            />
          </uni-forms-item>
          
          <uni-forms-item label="门禁编码" required>
            <uni-easyinput
              v-model="formData.door"
              placeholder="请输入门禁编码"
              :clearable="true"
            />
          </uni-forms-item>
          
          <uni-forms-item label="月租金" required>
            <uni-easyinput
              v-model="formData.monthPrice"
              placeholder="请输入月租金"
              type="number"
              :clearable="true"
            />
          </uni-forms-item>
          
          <uni-forms-item label="截止日期" required>
            <uni-datetime-picker
              v-model="formData.endDate"
              type="date"
              placeholder="请选择截止日期"
            />
          </uni-forms-item>
          
          <uni-forms-item label="备注">
            <uni-easyinput
              v-model="formData.remark"
              placeholder="请输入备注信息"
              type="textarea"
              :clearable="true"
            />
          </uni-forms-item>
        </view>

        <!-- 房东信息 -->
        <view class="form-section">
          <view class="section-title">房东信息</view>
          
          <uni-forms-item label="房东" required>
            <view class="landlord-select-container">
              <uni-easyinput
                v-model="landlordSearchText"
                placeholder="请输入房东姓名或手机号搜索"
                :clearable="true"
                @input="onLandlordSearchInput"
                @focus="onLandlordFocus"
              />
              <view v-if="showLandlordDropdown" class="landlord-dropdown">
                <view v-if="filteredLandlords.length === 0" class="no-data">
                  未找到匹配的房东
                </view>
                <view 
                  v-for="landlord in filteredLandlords" 
                  :key="landlord.value"
                  class="landlord-item"
                  @click="selectLandlord(landlord)"
                >
                  {{ landlord.text }}
                </view>
              </view>
            </view>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
import { createHouse, getDeptTree, getLandlordList } from '@/api/door/house'

export default {
  data() {
    return {
      formData: {
        country: '',
        province: '',
        city: '',
        district: '',
        street: '',
        village: '',
        address: '',
        door: '',
        accessNum: null,
        monthPrice: '',
        endDate: '',
        landlordId: '',
        landlordObj: null,
        deptId: '',
        remark: ''
      },
      rules: {
        address: {
          rules: [{
            required: true,
            errorMessage: '请输入详细地址'
          }]
        },
        door: {
          rules: [{
            required: true,
            errorMessage: '请输入门禁编码'
          }]
        },
        monthPrice: {
          rules: [{
            required: true,
            errorMessage: '请输入月租金'
          }]
        },
        endDate: {
          rules: [{
            required: true,
            errorMessage: '请选择截止日期'
          }]
        },
        landlordId: {
          rules: [{
            required: true,
            errorMessage: '请选择房东'
          }]
        },
        province: {
          rules: [{
            required: true,
            errorMessage: '请选择省份'
          }]
        },
        city: {
          rules: [{
            required: true,
            errorMessage: '请选择城市'
          }]
        },
        district: {
          rules: [{
            required: true,
            errorMessage: '请选择区县'
          }]
        },
        street: {
          rules: [{
            required: true,
            errorMessage: '请选择街道'
          }]
        },
        village: {
          rules: [{
            required: true,
            errorMessage: '请选择村/社区'
          }]
        }
      },
      // 地区数据
      deptTreeData: [],
      provinceList: [],
      cityList: [],
      districtList: [],
      streetList: [],
      villageList: [],
      // 房东数据（改为接口分页查询）
      landlordList: [],
      allLandlords: [], // 保留，不再一次性全量使用
      landlordSearchText: '',
      showLandlordDropdown: false,
      filteredLandlords: [],
      landlordLoading: false, // 新增：搜索加载态
      landlordSearchTimer: null // 新增：防抖计时器
    }
  },
  watch: {
    // 监听房东搜索关键词变化
    'formData.landlordId': {
      handler(newVal, oldVal) {
        // 当清空选择时，恢复显示前10条数据
        if (!newVal && oldVal) {
          this.landlordList = this.allLandlords.slice(0, 10)
        }
      }
    }
  },
  onLoad() {
    this.loadDeptTreeData()
    this.loadLandlordData()
  },
  onShow() {
    // 添加点击外部关闭下拉框的监听
    this.addClickOutsideListener()
  },
  onHide() {
    // 移除点击外部关闭下拉框的监听
    this.removeClickOutsideListener()
  },
  methods: {
    // 添加点击外部关闭下拉框的监听
    addClickOutsideListener() {
      this.clickOutsideHandler = (e) => {
        const target = e.target
        const container = document.querySelector('.landlord-select-container')
        if (container && !container.contains(target)) {
          this.showLandlordDropdown = false
        }
      }
      document.addEventListener('click', this.clickOutsideHandler)
    },
    
    // 移除点击外部关闭下拉框的监听
    removeClickOutsideListener() {
      if (this.clickOutsideHandler) {
        document.removeEventListener('click', this.clickOutsideHandler)
      }
    },
    goBack() {
      uni.navigateBack()
    },
    
    // 加载地区树形数据
    async loadDeptTreeData() {
      try {
        const response = await getDeptTree()
        if (response.code === 200) {
          this.deptTreeData = response.data
          this.processDeptTreeData()
        }
      } catch (error) {
        console.error('加载地区数据失败:', error)
        this.$modal.msgError('加载地区数据失败')
      }
    },
    
    // 处理地区树形数据
    processDeptTreeData() {
      // 从树形数据中提取省份列表
      this.provinceList = []
      this.deptTreeData.forEach(company => {
        if (company.children && company.children.length > 0) {
          company.children.forEach(province => {
            this.provinceList.push({
              value: province.id,
              text: province.label
            })
          })
        }
      })
    },
    
    // 加载房东数据
    async loadLandlordData() {
      try {
        const response = await getLandlordList({
          pageNum: 1,
          pageSize: 1000, // 获取全部数据
          roleId: 100
        })
        console.log('房东接口返回数据:', response)
        if (response.code === 200 && response.rows) {
          // 处理房东数据
          const allLandlords = response.rows.map(item => ({
            value: item.userId,
            text: `${item.nickName || item.userName}（${item.phonenumber}）`
          }))
          
          // 保存全部数据
          this.allLandlords = allLandlords
          // 默认显示前10条数据
          this.filteredLandlords = allLandlords.slice(0, 10)
          
          console.log('房东列表初始化完成，总数:', allLandlords.length, '默认显示:', this.filteredLandlords.length)
        } else {
          console.warn('房东接口返回异常:', response);
          this.allLandlords = [];
          this.filteredLandlords = [];
        }
        
        // 如果接口没有数据，使用测试数据
        if (this.allLandlords.length === 0) {
          console.log('使用测试房东数据')
          const testData = [
            { value: 101, text: '何志龙（16635049149）' },
            { value: 102, text: '银龙（13599879000）' },
            { value: 103, text: '张无忌（13403470089）' },
            { value: 104, text: '测试房东信息（16635049145）' },
            { value: 105, text: '张学路（18612511092）' }
          ]
          this.allLandlords = testData
          this.filteredLandlords = testData
        }
      } catch (error) {
        console.error('加载房东数据失败:', error)
        // 使用测试数据
        const testData = [
          { value: 101, text: '何志龙（16635049149）' },
          { value: 102, text: '银龙（13599879000）' },
          { value: 103, text: '张无忌（13403470089）' },
          { value: 104, text: '测试房东信息（16635049145）' },
          { value: 105, text: '张学路（18612511092）' }
        ]
        this.allLandlords = testData
        this.filteredLandlords = testData
        this.$modal.msgError('加载房东数据失败，使用测试数据')
      }
    },
    
    // 房东变化
    onLandlordChange(value) {
      const landlord = this.landlordList.find(item => item.value === value)
      if (landlord) {
        this.formData.landlordObj = {
          id: landlord.value,
          name: landlord.text
        }
      } else {
        this.formData.landlordObj = null
      }
    },
    
    // 房东搜索输入框输入事件（改为接口查询 + 防抖）
    onLandlordSearchInput(val) {
      const value = typeof val === 'string' ? val : (val && val.detail ? val.detail.value : '')
      this.landlordSearchText = value
      this.showLandlordDropdown = true
      // 防抖
      if (this.landlordSearchTimer) clearTimeout(this.landlordSearchTimer)
      this.landlordSearchTimer = setTimeout(() => {
        this.fetchLandlordsByKeyword(this.landlordSearchText)
      }, 300)
    },

    // 聚焦时拉取默认列表（第一页）
    onLandlordFocus() {
      this.showLandlordDropdown = true
      this.fetchLandlordsByKeyword('')
    },

    // 后端查询房东（分页/条件）
    async fetchLandlordsByKeyword(keyword) {
      try {
        this.landlordLoading = true
        const params = {
          pageNum: 1,
          pageSize: 20,
          roleId: 100
        }
        // 根据实际后端字段，尽可能兼容多字段
        if (keyword && keyword.trim()) {
          const k = keyword.trim()
          // 常见字段尝试
          params.nickName = k
          // params.userName = k
          // params.phonenumber = k
          // // 若后端支持统一关键字
          // params.keyword = k
        }
        const res = await getLandlordList(params)
        if (res && res.code === 200) {
          const rows = res.rows || []
          this.filteredLandlords = rows.map(item => ({
            value: item.userId,
            text: `${item.nickName || item.userName || ''}（${item.phonenumber || ''}）`
          }))
        } else {
          this.filteredLandlords = []
        }
      } catch (e) {
        this.filteredLandlords = []
      } finally {
        this.landlordLoading = false
      }
    },

    // 选择房东
    selectLandlord(landlord) {
      this.formData.landlordId = landlord.value
      this.formData.landlordObj = {
        id: landlord.value,
        name: landlord.text
      }
      this.landlordSearchText = landlord.text
      this.showLandlordDropdown = false
    },
    

    
    // 省份变化
    onProvinceChange(value) {
      this.formData.city = ''
      this.formData.district = ''
      this.formData.street = ''
      this.formData.village = ''
      this.cityList = []
      this.districtList = []
      this.streetList = []
      this.villageList = []
      
      // 根据选择的省份加载城市数据
      this.deptTreeData.forEach(company => {
        if (company.children && company.children.length > 0) {
          const province = company.children.find(p => p.id === value)
          if (province && province.children && province.children.length > 0) {
            this.cityList = province.children.map(city => ({
              value: city.id,
              text: city.label
            }))
          }
        }
      })
    },
    
    // 城市变化
    onCityChange(value) {
      this.formData.district = ''
      this.formData.street = ''
      this.formData.village = ''
      this.districtList = []
      this.streetList = []
      this.villageList = []
      
      // 根据选择的城市加载区县数据
      this.deptTreeData.forEach(company => {
        if (company.children && company.children.length > 0) {
          company.children.forEach(province => {
            if (province.children && province.children.length > 0) {
              const city = province.children.find(c => c.id === value)
              if (city && city.children && city.children.length > 0) {
                this.districtList = city.children.map(district => ({
                  value: district.id,
                  text: district.label
                }))
              }
            }
          })
        }
      })
    },
    
    // 区县变化
    onDistrictChange(value) {
      this.formData.street = ''
      this.formData.village = ''
      this.streetList = []
      this.villageList = []
      
      // 根据选择的区县加载街道数据
      this.deptTreeData.forEach(company => {
        if (company.children && company.children.length > 0) {
          company.children.forEach(province => {
            if (province.children && province.children.length > 0) {
              province.children.forEach(city => {
                if (city.children && city.children.length > 0) {
                  const district = city.children.find(d => d.id === value)
                  if (district && district.children && district.children.length > 0) {
                    this.streetList = district.children.map(street => ({
                      value: street.id,
                      text: street.label
                    }))
                  }
                }
              })
            }
          })
        }
      })
    },
    
    // 街道变化
    onStreetChange(value) {
      this.formData.village = ''
      this.villageList = []
      
      // 根据选择的街道加载村/社区数据
      this.deptTreeData.forEach(company => {
        if (company.children && company.children.length > 0) {
          company.children.forEach(province => {
            if (province.children && province.children.length > 0) {
              province.children.forEach(city => {
                if (city.children && city.children.length > 0) {
                  city.children.forEach(district => {
                    if (district.children && district.children.length > 0) {
                      const street = district.children.find(s => s.id === value)
                      if (street && street.children && street.children.length > 0) {
                        this.villageList = street.children.map(village => ({
                          value: village.id,
                          text: village.label
                        }))
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    },
    
    // 村/社区变化
    onVillageChange(value) {
      this.formData.deptId = value
    },
    
    // 保存地址
    async saveAddress() {
      try {
        // 表单验证
        const valid = await this.$refs.form.validate()
        if (!valid) {
          return
        }
        
        // 数据转换
        const submitData = {
          ...this.formData,
          monthPrice: Number(this.formData.monthPrice),
          accessNum: this.formData.accessNum || null
        }
        
        this.$modal.loading('正在保存...')
        
        const response = await createHouse(submitData)
        
        this.$modal.closeLoading()
        
        if (response.code === 200) {
          this.$modal.msgSuccess('保存成功')
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          this.$modal.msgError(response.msg || '保存失败')
        }
      } catch (error) {
        this.$modal.closeLoading()
        this.$modal.msgError('网络异常，请稍后重试')
        console.error('保存地址失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.address-input-container {
  background-color: #f5f6f7;
  min-height: 100vh;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-save {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.form-container {
  padding: 20rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    padding-bottom: 15rpx;
    border-bottom: 1px solid #f0f0f0;
  }
}

:deep(.uni-forms-item) {
  margin-bottom: 20rpx;
  
  .uni-forms-item__label {
    font-size: 28rpx;
    color: #333;
  }
  
  .uni-easyinput__content,
  .uni-data-select {
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    padding: 0 20rpx;
    height: 80rpx;
  }
}

.landlord-select-container {
  position: relative;
  width: 100%;

  .uni-easyinput__content {
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    padding: 0 20rpx;
    height: 80rpx;
    background-color: #fff;
  }

  .landlord-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    max-height: 300rpx;
    overflow-y: auto;
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    z-index: 1000;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    margin-top: 4rpx;
  }

  .no-data {
    padding: 20rpx;
    text-align: center;
    color: #999;
    font-size: 28rpx;
  }

  .landlord-item {
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    &:active {
      background-color: #e0e0e0;
    }
  }
}
</style> 